using System;
using UnityEngine;

namespace NodeCanvas.StateMachines
{
	public abstract class FSMState : Node, IState
	{
		public float elapsedTime { get; private set; }

		public override int maxInConnections
		{
			get
			{
				return -1;
			}
		}

		public override int maxOutConnections
		{
			get
			{
				return -1;
			}
		}

		public sealed override Type outConnectionType
		{
			get
			{
				return typeof(FSMConnection);
			}
		}

		public FSM FSM
		{
			get
			{
				return (FSM)base.graph;
			}
		}

		public void Finish()
		{
			Finish(true);
		}

		protected void Finish(ValueType inSuccess)
		{
			base.enabled = false;
			base.status = Status.Success;
		}

		public sealed override void OnGraphStarted()
		{
			Init();
		}

		public sealed override void OnGraphStoped()
		{
			base.status = Status.Resting;
		}

		public sealed override void OnGraphPaused()
		{
			if (base.status == Status.Running)
			{
				Pause();
			}
		}

		protected sealed override Status OnExecute()
		{
			if (base.status == Status.Resting || base.status == Status.Running)
			{
				base.status = Status.Running;
				base.enabled = true;
				Enter();
			}
			return base.status;
		}

		public void OnUpdate()
		{
			elapsedTime += Time.deltaTime;
			if (!CheckTransition() && base.status == Status.Running)
			{
				Stay();
			}
		}

		private bool CheckTransition()
		{
			for (int i = 0; i < base.outConnections.Count; i++)
			{
				FSMConnection fSMConnection = base.outConnections[i] as FSMConnection;
				if (fSMConnection.CheckCondition(base.graphAgent, base.graphBlackboard) && (base.status != Status.Running || fSMConnection.condition != null))
				{
					FSM.EnterState(fSMConnection.targetNode as FSMState);
					fSMConnection.connectionStatus = Status.Success;
					return true;
				}
			}
			return false;
		}

		protected sealed override void OnReset()
		{
			elapsedTime = 0f;
			Exit();
		}

		protected virtual void Init()
		{
		}

		protected virtual void Enter()
		{
		}

		protected virtual void Stay()
		{
		}

		protected virtual void Exit()
		{
		}

		protected virtual void Pause()
		{
		}
	}
}
